from google.appengine.api import users
import copy, datetime

class PageState:
    state = ''
    params = {}
    perm_params = {}

def parse_state(s):
    state = PageState()
    if s == '':
        return state
    c = s.strip().split(',')
    for i in range(0, len(c) / 2):
        state.params[c[i*2]] = c[i*2 + 1]
    return state

def geturl(perm_params, new_params):
    s = '?s='
    for k, v in new_params.iteritems():
        s += k + ',' + v + ','
    s = s.rstrip(',')
    for k, v in perm_params.iteritems():
        s += '&' + k + '=' + v
    return s

def calc_table_params(id, params, sort):
    new_params = copy.deepcopy(params)
    order = 'a'
    sid = 's%d' % id
    oid = 'o%d' % id
    if sid in params and sort == params[sid] and oid in params:
        order = params[oid]
        if order == 'a':
            order = 'd'
        else:
            order = 'a'
    new_params[sid] = sort
    new_params[oid] = order
    return new_params

def sort_lines(id, lines, params):
    sort = lines[0][0]
    if 's%d' % id in params:
        sort = params['s%d' % id]
    order = 'a'
    if 'o%d' % id in params:
        order = params['o%d' % id]
    idx = -1
    for c in lines[0]:
        idx += 1
        if c == sort:
            break
    lines = lines[1:]
 
    if idx >= 0:
        lines = sorted(lines, key=lambda row: row[idx], reverse = order == 'd')

    return lines

def format_table(id, lines, pgstate, row_template = ''):
    text = '<table border="1">\n    <tr>\n<th>#</th>\n'
    for th in lines[0]:
        if th == '':
            continue
        new_params = calc_table_params(id, pgstate.params, th)
        text += '        <th><a href="' + \
                geturl(pgstate.perm_params, new_params) + \
                '">' + th + '</a></th>\n'
    text += '    </tr>\n'

    lines = sort_lines(id, lines, pgstate.params)

    cnt = 0
    for line in lines:
        text += '    <tr class="tr%d">\n' % (cnt % 2)
        text += '        <td width="30px"><input accesskey="x" type="checkbox" name="sel" value="%s"></td>' % str(line[0])
        cnt += 1
        if row_template == '':
           for col in line:
                if type(col) == float:
                    text += '        <td>%.02f</td>\n' % col
                else:
                    text += '        <td>' + str(col) + '</td>\n'
        else:
            text += row_template % line
        text += '    </tr>\n'
    text += '</table>\n'
    return text

def get_menu():
    user = users.get_current_user()
    if not user:
        text = ("<a href=\"%s\">Sign in or register</a>." % users.create_login_url("/"))
    else:
        text = 'user: ' + user.nickname()
        text += ' <a href="/">main</a>\n'
        text += ' <a href="/details">details</a>\n'
        text += ' <a href="' + users.create_logout_url("/") + '">logout</a>\n'
        if users.is_current_user_admin():
            text += '<a href="/admin/view">view</a>\n'
            text += '<a href="/admin/parse">parse</a>\n'
            text += '<a href="/admin/reset">reset</a>\n'
        text += '<br><br>\n'
 
    return text

page = '''
<html>
<head>
    <title>%s</title>
    <link type="text/css" rel="stylesheet" href="/files/main.css" />
</head>
<body>
%s
</body>
</html>
'''

form = '''
<form method="POST" action="/admin/op">
%s
<br/>
<select name="op">
    <option value="0">set tag</option>
    <option value="shop">--shop</option>
    <option value="cloth">--cloth</option>
    <option value="food">--food</option>
    <option value="home">--home</option>
    <option value="fun">--fun</option>
    <option value="car">--car</option>
    <option value="misc">--misc</option>
    <option value="pharmacy">--pharmacy</option>
    <option value="health">--health</option>
    <option value="comm">--comm</option>
    <option value="bilz">--bilz</option>
    <option value="apt">--apt</option>
    <option value="filtered">--filtered</option>
    <option value="--clear--">clear atag</option>
    <option value="--delete--">delete</option>
    <option value="--parse--">parse</option>
</select>
<input type="submit" name="apply" value="Apply" />
</form>
'''

def format_page(title, body):
    text = ''
    if users.is_current_user_admin():
        text = form % body
    else:
        text = body
    return page % (title, text)

